package com.example.kotlindemo_room

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

/**
 * 创建studentDao进行数据库操作
 */
class StudentRepository(context: Context) {
    lateinit var studentDao: StudentDao
    lateinit var context: Context

    init {
        val myDataBase = MyDataBase.getInstance(context)
        studentDao = myDataBase.getStudentDao()
        this.context = context
    }

    fun InsertStuDent() {
        InsertStuTask(studentDao).start()
//        InsertStuTask2(studentDao,Student( "张三", 13)).start()
//        InsertStuTask2(studentDao,Student( "李四", 15)).start()
    }
    fun InsertStuDent2(student: Student) {
        InsertStuTask2(studentDao,student).start()
    }

    fun DeleteStuDent(student: Student) {
        DeleteStuTask(studentDao, student).start()
    }

    fun UpDateStuDent(student: Student) {
        UpDateStuTask(studentDao, student).start()
    }

    fun DeleteAllStuDent() {
        DeleteAllStuTask(studentDao).start()
    }



    class InsertStuTask(val studentDao: StudentDao) : Thread() {
        override fun run() {
            studentDao.insertStudent(Student( "张三",18))
            studentDao.insertStudent(Student( "张三2",19))
            super.run()
        }
    }
    class InsertStuTask2(val studentDao: StudentDao,val student: Student) : Thread() {
        override fun run() {
            studentDao.insertStudent(student)
            super.run()
        }
    }

    class UpDateStuTask(val studentDao: StudentDao, val stu: Student) : Thread() {
        override fun run() {
            studentDao.upDateStudent(stu)
            super.run()
        }
    }

    class DeleteStuTask(val studentDao: StudentDao, val stu: Student) : Thread() {
        override fun run() {
            studentDao.deletStudent(stu)
            super.run()
        }
    }

    class DeleteAllStuTask(val studentDao: StudentDao) : Thread() {
        override fun run() {
            studentDao.deletAllStudent()
            super.run()
        }
    }

    /**
     * LiveData配合Room，返回LiveData类型，内部会自动开启一个线程。这时候就不需要再新建子线程操作数据库了
     */
    fun getAllStuDent():LiveData<List<Student>> {
        return studentDao.getAllStudent()
    }
}